package com.byit.dx;

import com.alibaba.fastjson.JSONObject;
import com.byit.jgpush.JgPushService;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SendMessService {
	private static final Logger logger = LoggerFactory.getLogger(SendMessService.class);

	private static HttpClient httpclient;

	private static final String SMS_SIGN = "【智慧江油】";

	private static final String START_TEXT = "您的验证码:";

	private static final String END_TEXT = ",五分钟内有效。";

	private static final String APPROVAL_START_TEXT = "您的";

	private static final String APPROVAL_END_TEXT = "，请查询相关信息";
	/**
	 *  短信发送静态方法
	 * @param text 发送短信内容，不加签名
	 * @param number 手机号码（11位）
	 */
	@SuppressWarnings("deprecation")
	public static boolean sendSms(String text,String number){

		try {

			if (text.trim().length()>60) {
				logger.error("短信内容不得超过60个字符");
				throw new Exception("短信内容不得超过60个字符");
			}

			if (number.trim().length()!=11) {
				logger.error("手机号码长度不正确");
				throw new Exception("手机号码长度不正确");
			}
            return send(text.trim()+SMS_SIGN,number);
		} catch (Exception ex) {
			logger.error(ex.getMessage());
			ex.printStackTrace();
			return false;
		}
	}

	/**
	 * 短信发送验证码静态方法
	 * @param code 验证码，长度不得超过6位
	 * @param number 手机号码（11位）
	 */
	@SuppressWarnings("deprecation")
	public static boolean sendSmsForCode(String code,String number){

		try {

			if (code.length()!=6) {
				logger.error("验证码长度不得超过6位");
				throw new Exception("验证码长度不得超过6位");
			}

			if (number.length()!=11) {
				logger.error("手机号码长度不正确");
				throw new Exception("手机号码长度不正确");
			}
            return send(START_TEXT+code+END_TEXT+SMS_SIGN,number);

		} catch (Exception ex) {
			logger.error(ex.getMessage());
			ex.printStackTrace();
			return false;
		}
	}


	/**
	 *  自定义短信发送
	 * @param text 发送短信内容，不加签名
	 * @param number 手机号码（11位）
	 */
	@SuppressWarnings("deprecation")
	public static boolean sendMessage(String text,String number){

		try {

			if (text.trim().length()>60) {
				logger.error("短信内容不得超过60个字符");
				throw new Exception("短信内容不得超过60个字符");
			}

			if (number.trim().length()!=11) {
				logger.error("手机号码长度不正确");
				throw new Exception("手机号码长度不正确");
			}
			return send(APPROVAL_START_TEXT+text+APPROVAL_END_TEXT+SMS_SIGN,number);

		} catch (Exception ex) {
			logger.error(ex.getMessage());
			ex.printStackTrace();
			return false;
		}
	}

	private static boolean send(String text,String phone){
        try {

            httpclient = new SSLClient();
            String url = "https://dx.ipyy.net/sms.aspx";
            //改为实际账号名
            String accountName="AC00743";
            //改为实际发送密码
            String password="AC0074345";

            HttpPost post = new HttpPost(url);
            post.setHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
            List<NameValuePair> nvps = new ArrayList<>();
            nvps.add(new BasicNameValuePair("action","send"));
            nvps.add(new BasicNameValuePair("userid", ""));
            nvps.add(new BasicNameValuePair("account", accountName));
            nvps.add(new BasicNameValuePair("password", password));
            //多个手机号用逗号分隔
            nvps.add(new BasicNameValuePair("mobile", phone));
            nvps.add(new BasicNameValuePair("content", text));
            nvps.add(new BasicNameValuePair("sendTime", ""));
            nvps.add(new BasicNameValuePair("extno", ""));

            post.setEntity(new UrlEncodedFormEntity(nvps,HTTP.UTF_8));

            HttpResponse response = httpclient.execute(post);

            HttpEntity entity = response.getEntity();
            // 将字符转化为XML
            String returnString=EntityUtils.toString(entity, "UTF-8");
            Document doc = DocumentHelper.parseText(returnString);
            // 获取根节点
            Element rootElt = doc.getRootElement();
            // 获取根节点下的子节点的值
            String returnstatus = rootElt.elementText("returnstatus").trim();
            String message = rootElt.elementText("message").trim();
            String remainpoint = rootElt.elementText("remainpoint").trim();
            //String taskID = rootElt.elementText("taskID").trim();
            //String successCounts = rootElt.elementText("successCounts").trim();

            EntityUtils.consume(entity);

			/*
			System.out.println("返回状态为：" + returnstatus);
			System.out.println("返回信息提示：" + message);
			System.out.println("返回余额：" + remainpoint);
			System.out.println("返回任务批次：" + taskID);
			System.out.println("返回成功条数：" + successCounts);
			*/
            logger.info("短信发送：返回状态为：" + returnstatus+"___"+"返回信息提示：" + message+"___"+"返回余额条数：" + remainpoint);
            if ("100".equals(remainpoint)) {
                logger.error("当前短信平台，剩余短信条数不足，当前条数为："+remainpoint);
            }

            if ("Success".equals(returnstatus)) {
                return true;
            }else if ("Fail".equals(returnstatus)) {
                return false;
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            ex.printStackTrace();
            return false;
        }
        return false;
    }


	@Autowired
	private  JgPushService jgPushService;
	public static void main(String[] args) {

			Map<String, String> param = new HashMap<>();
                param.put("title", "主题");
                param.put("cont", "内容");

                Map<String, String> typeMap = new HashMap<>();
                typeMap.put("level","1");
               // typeMap.put("publisher", appMessageNotice.getPublisher().toString());

                param.put("type", JSONObject.toJSONString(typeMap));

                //发布者 默认0 0:系统公告 1.政府公告
               // param.put("publisher", appMessageNotice.getPublisher().toString());
		//jgPushService.jpushAllByAndroidIOS(param);
		System.out.println(sendSms("能收到吗", "13558787376"));
	}
}
